package com.atguigu.gulimall.order.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName GuliFeignConfig
 * @Description TODO
 * @Detail detail
 * @Author MyPC
 * @Date 2020/7/19
 * @Version 1.0
 */
@Configuration
public class GuliFeignConfig {
    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor(){
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                //异步调用是requestAttributes有可能为空
                if(requestAttributes !=null){
                    //旧请求
                    HttpServletRequest request = requestAttributes.getRequest();
                    //同步旧请求的请求头到新请求，主要是cookie
                    String cookie = request.getHeader("cookie");
                    requestTemplate.header("cookie",cookie);
                }
            }
        };
    }
}
